const daoUser = require('../dao/daoUser')
module.exports = {
  getBooks(req, resp) {
    let { page, type, search, status_, region, update_date, chapter_count } = req.query;

    let sqlSearch = [], sql = ''; 
    if (type) sqlSearch.push(`type='${decodeURIComponent(type)}'`);
    if (status_) sqlSearch.push(`status_=${decodeURIComponent(status_)}`);
    if (region) sqlSearch.push(`region='${decodeURIComponent(region)}'`);
    if (search && search.split(' ').length > 1) {
      search.split(' ').forEach(element => {
        if (element) sqlSearch.push(`name_ LIKE '%${decodeURIComponent(element)}%'`);
      });
    } else {
      console.log(`search`, search)
      if (search) sqlSearch.push(`name_ LIKE '%${decodeURIComponent(search)}%'`);
    }
    sqlSearch.push(`name_  IS NOT NULL`);

    if (sqlSearch.length > 0) {
      sql = `WHERE ${sqlSearch.join(' AND ')}`;
    }

    if (update_date == '最旧') {
      // ORDER BY books.update_date DESC  -- 或 ASC，根据需求选择升序或降序
      // DESC 表示降序（从最新到最旧）。
      // 如果需要升序（从最旧到最新），改为 ASC。
      // 如果省略排序方向（如 ORDER BY books.update_date），默认是 ASC
      sql += ' ORDER BY update_date ASC  '
    } else {
      sql += ' ORDER BY update_date DESC  '
    }

    console.log(`getBooks = `, req.query, sql)

    daoUser.getBooksFactorLimit(Number(chapter_count) || 0, sql, Number(page ? page - 1 : 0) * 60, 60)
      .then(d => { resp.send(d); })
      .catch(e => { resp.status(404), resp.send(e.message) });
  },
  getBook(req, resp) {
    let { id } = req.query;
    daoUser.getBook([id])
      .then(d => { resp.send(d); })
      .catch(e => { resp.status(404), resp.send(e.message) });
  },
  getChapterImg(req, resp) {
    let { id } = req.query;
    daoUser.getImgs([id])
      .then(d => { resp.send(d); })
      .catch(e => { resp.status(404), resp.send(e.message) });
  },
  updateBaseUrl(req, resp) {
    let { id, url } = req.query;
    daoUser.updateBase_url([url, Number(id)])
      .then(d => { resp.send(d); })
      .catch(e => { resp.status(404), resp.send(e.message) });
  },
  getBase_url(req, resp) {
    daoUser.getBase_url()
      .then(d => { resp.send(d); })
      .catch(e => { resp.status(404), resp.send(e.message) });
  },
}